<template>
    <el-drawer title="一键调价" :visible.sync="drawer.show" size="30%" custom-class="add-drawer">
        <div style="padding: 0 20px; margin-bottom: 30px">
            <el-divider></el-divider>
            <div>
                <p style="font-size: 23px">油品选择</p>
                <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll"
                    @change="handleCheckAllChange">全选</el-checkbox>
                <div style="margin: 15px 0"></div>
                <el-checkbox-group v-model="checkedList" @change="handleCheckedCitiesChange">
                    <el-checkbox v-for="item in oilsList" :label="item.oilId" :key="item.oilId">{{ item.oilName
                    }}</el-checkbox>
                </el-checkbox-group>
                <el-divider></el-divider>
                <div v-for="oil in oilsForm.stationOillGunPriceList" :key="oil.oilId">
                    <p style="font-size: 23px">油品名称：{{ oil.oilName }}</p>
                    <el-form :model="oil" :rules="oilListRules" ref="oilList" label-width="130px" label-position="left">
                        <el-form-item label="发改委价" prop="oilOfficialPrice">
                            <el-input v-model="oil.oilOfficialPrice" placeholder="请输入发改委价"></el-input>
                        </el-form-item>
                        <el-form-item label="油站价" prop="oilStationPrice">
                            <el-input v-model="oil.oilStationPrice" placeholder="请输入油站价"></el-input>
                        </el-form-item>
                        <el-form-item label="优惠价(仅展示用)" prop="discountPrice">
                            <el-input v-model="oil.discountPrice" placeholder="请输入优惠价"></el-input>
                        </el-form-item>
                    </el-form>
                    <el-divider></el-divider>
                </div>
            </div>
            <p style="font-size: 23px" class="t">生效日期</p>
            <el-form :model="oilsForm" ref="oilForm" :rules="oilListRules">
                <div>
                    <el-checkbox v-model="effectDateStatus" @change="effecgDateChange">立即生效</el-checkbox>
                </div>
                <el-form-item prop="effectDate">
                    <el-date-picker v-model="effectDay" align="right" type="date" value-format="yyyy-MM-dd"
                        placeholder="选择日期" style="margin-right: 10px">
                    </el-date-picker>
                    <el-time-select v-model="effectTime" :picker-options="{
                        start: '00:00',
                        step: '01:00',
                        end: '23:00',
                    }" placeholder="选择时间点">
                    </el-time-select>
                    <!-- <el-date-picker v-model="oilsForm.effectDate" type="datetime" format="yyyy-MM-dd HH"
                value-format="yyyy-MM-dd HH">
                    </el-date-picker> -->
                </el-form-item>
                <!-- <el-divider></el-divider> -->
                <p style="font-size: 23px">调价消息推送时间</p>
                <div>
                    <el-checkbox v-model="pushDateStatus" @change="pushDateChange">立即推送</el-checkbox>
                </div>
                <el-form-item prop="pushDate">
                    <el-date-picker v-model="oilsForm.pushDate" type="datetime" value-format="yyyy-MM-dd HH:mm:ss">
                    </el-date-picker>
                </el-form-item>
            </el-form>
        </div>
        <div style="text-align: right; padding: 0 20px; margin-bottom: 20px">
            <el-button @click="drawer.show = false">取消</el-button>
            <el-button type="primary" @click="handleSubmit">确认</el-button>
        </div>
    </el-drawer>
</template>
<script>
import { formatDate } from "@/utils/index";
import { getListByEnterprise, updateOilGunPrice } from "@/api/system/dept";
export default {
    props: {
        parm: {
            type: Object,
            default: null,
        },
    },
    data() {
        var validateDate = (rule, value, callback) => {
            if (!this.effectDay) {
                return callback(new Error("请选择生效日期"));
            }
            const now = formatDate(new Date());
            const str = now.split(" ");
            const day = str[0];
            const time = str[1].substring(0, 2) + ":00";
            if (day > this.effectDay) {
                return callback(new Error("生效日期不能小于当前日期"));
            }
            if (day === this.effectDay) {
                if (time >= this.effectTime) {
                    return callback(new Error("生效时间不能小于当前时间"));
                }
            }
            if (!this.effectTime) {
                return callback(new Error("请选择时间点"));
            }
            callback();
        };
        return {
            effectDay: "",
            effectTime: "",
            drawer: {
                show: this.parm ? this.parm.drawerShow : false,
            },
            isIndeterminate: false,
            oilsList: [],
            oilOptionList: [],
            checkedList: [],
            checkAll: false,
            oilsForm: {
                stationOillGunPriceList: [],
                effectDate: "",
                pushDate: "",
            },
            oilListRules: {
                oilOfficialPrice: [
                    { required: true, message: "请输入发改委指导价", trigger: "blur" },
                ],
                oilStationPrice: [
                    { required: true, message: "请输入油站价", trigger: "blur" },
                ],
                effectDate: [
                    { required: true, validator: validateDate, trigger: "change" },
                ],
            },
            effectDateStatus: false,
            pushDateStatus: false,
        };
    },
    methods: {
        clearData() {
            this.oilsForm = {
                stationOillGunPriceList: [],
                effectDate: "",
                pushDate: "",
            };
            this.effectDay = "";
            this.effectTime = "";
            this.effectDateStatus = false;
            this.pushDateStatus = false;
            this.$nextTick(() => {
                this.$refs.oilForm.clearValidate();
            });
        },
        effecgDateChange(val) {
            if (val) {
                // this.oilsForm.effectDate = this.formatter(new Date(), 'yyyy-MM-dd hh:mm:ss');
                const now = new Date();
                this.effectDay = this.formatter(now, "yyyy-MM-dd");
                // const time = new Date(now.getTime() + 60 * 60 * 1000)
                this.effectTime = this.formatter(now, "hh:mm");
            }
        },
        pushDateChange(val) {
            // if (val) {
            // this.oilsForm.pushDate = this.formatter(new Date(), 'yyyy-MM-dd hh:mm:ss');
            // }
        },
        formatter(thistime, fmt) {
            let $this = new Date(thistime);
            let o = {
                "M+": $this.getMonth() + 1,
                "d+": $this.getDate(),
                "h+": $this.getHours(),
                "m+": $this.getMinutes(),
                "s+": $this.getSeconds(),
                "q+": Math.floor(($this.getMonth() + 3) / 3),
                S: $this.getMilliseconds(),
            };
            if (/(y+)/.test(fmt)) {
                fmt = fmt.replace(
                    RegExp.$1,
                    ($this.getFullYear() + "").substr(4 - RegExp.$1.length)
                );
            }
            for (var k in o) {
                if (new RegExp("(" + k + ")").test(fmt)) {
                    fmt = fmt.replace(
                        RegExp.$1,
                        RegExp.$1.length === 1
                            ? o[k]
                            : ("00" + o[k]).substr(("" + o[k]).length)
                    );
                }
            }
            return fmt;
        },
        handleSubmit() {
            const isPush = this.pushDateStatus ? 1 : 0;
            if (this.oilsForm.stationOillGunPriceList.length < 1) {
                return this.$message.error("请选择油品！！！");
            }
            const form1 = new Promise((resolve, reject) => {
                this.$refs["oilList"].forEach((item) => {
                    item.validate((valid) => {
                        if (valid) resolve();
                    });
                });
            });
            const form2 = new Promise((resolve, reject) => {
                this.$refs["oilForm"].validate((valid) => {
                    if (valid) resolve();
                });
            });

            Promise.all([form1, form2]).then(() => {
                if (this.effectDateStatus) {
                    delete this.oilsForm.effectDate;
                }
                this.oilsForm.effectDate =
                    this.effectDay + " " + this.effectTime + ":00";
                updateOilGunPrice({ ...this.oilsForm, isPush }).then((res) => {
                    if (res && res.code === 200) {
                        this.$message.success(res.msg);
                        this.$emit("successData");
                    } else {
                        this.$message.error(res.msg);
                    }
                });
            });
        },
        getListByEnterprise() {
            this.checkedList = [];
            this.checkAll = false;
            this.isIndeterminate = false;
            getListByEnterprise().then((res) => {
                if (res && res.data) {
                    res.data.forEach((item) => {
                        item = Object.assign(item, {
                            oilOfficialPrice: "",
                            oilStationPrice: "",
                            discountPrice: "",
                        });
                    });
                    this.oilOptionList = res.data;
                    this.oilsList = this.oilOptionList;
                } else {
                    this.oilOptionList = [];
                    this.oilsList = [];
                }
            });
        },
        handleCheckAllChange(val) {
            let list = val ? this.oilOptionList : [];
            if (list.length > 0) {
                this.oilsForm.stationOillGunPriceList = [];
                list.forEach((item) => {
                    this.checkedList.push(item.oilId);
                    this.oilsForm.stationOillGunPriceList.push(item);
                });
            } else {
                this.checkedList = [];
                this.oilsForm.stationOillGunPriceList = [];
            }
            this.isIndeterminate = false;
        },
        handleCheckedCitiesChange(value) {
            let checkedCount = value.length;
            this.checkAll = checkedCount === this.oilsList.length;
            this.isIndeterminate =
                checkedCount > 0 && checkedCount < this.oilsList.length;
            this.oilsForm.stationOillGunPriceList = [];
            this.oilsList.forEach((item, index) => {
                if (value.includes(item.oilId)) {
                    this.oilsForm.stationOillGunPriceList.push(item);
                }
            });
        },
    },
    watch: {
        parm(newValue) {
            this.drawer.show = newValue.drawerShow;
        },
    },
};
</script>
<style lang="scss" scoped>
::v-deep .add-drawer {
    overflow-y: auto;
}

::v-deep .el-drawer__header {
    margin-bottom: 0 !important;
}

.t {
    &::before {
        content: "*";
        color: red;
        margin-right: 5px;
    }
}
</style>
